package com.project.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 图片上传帮助类
 * @Author: wangzhiqiang
 * @CreateDate: 2020-03-25 16:52
 * @Version: 1.0
 */
@Component
public class ImgUtil {

    Logger LOGGER = LoggerFactory.getLogger(ImgUtil.class);

    /**
     * 单张图片的上传
     * @param multipartFile
     * @param path 如：/opt/tomcat/webapps/elephant-family-img/portrait/
     * @return
     */
    public String uploadImg(MultipartFile multipartFile, String path) {
        //图片按天分组
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String day = dateFormat.format(new Date());
        path = path + day + "/";

        File filePath = new File(path);
        //查询是否有文件夹的存在，如无就创建
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        String filename = multipartFile.getOriginalFilename();
        String newfilename = System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
        try {
            File file = new File(path + newfilename);
            multipartFile.transferTo(file);
            //Thumbnails.of(file).scale(0.50f).toFile(path + newfilename);
            return newfilename;
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return null;
    }

    /**
     * 多张图片上传
     * @param multipartFiles
     * @param path
     * @return
     */
    public List<String> uploadImg(MultipartFile[] multipartFiles, String path) {
        //图片按天分组
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String day = dateFormat.format(new Date());
        path = path + day + "/";

        File filePath = new File(path);

        List<String> returnlist = new ArrayList<>();
        if (multipartFiles != null) {
            //判断这个文件夹是否存在，不存在就创建
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            if (multipartFiles != null && multipartFiles.length > 0) {
                for (int i = 0; i < multipartFiles.length; i++) {
                    //定义将文件以文件数组的方式存放
                    MultipartFile file = multipartFiles[i];
                    //得到文件的原始名称
                    String filename = file.getOriginalFilename();
                    //按循环的方式进行将图片命名，但是文件夹的名称的命名方式是根据添加数据的ID进行储存
                    String newFilename = System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
                    //图片存储在这个ID下的文件夹
                    LOGGER.info(newFilename);
                    try {
                        File file1 = new File(path + newFilename);
                        file.transferTo(file1);
                        //Thumbnails.of(file1).scale(0.50f).toFile(path + newFilename);
                        returnlist.add(newFilename);
                    } catch (Exception e) {
                        System.out.println(e.toString());
                    }
                }
                return returnlist;
            }
        }
        return null;
    }

    /**
     * 下载文件
     * @param response
     * @param path
     * @param fileName
     */
    public static void downloadLocal(HttpServletResponse response, String path, String fileName) {
        FileInputStream fileIn = null;
        ServletOutputStream out = null;
        try {
            //String fileName = new String(fileNameString.getBytes("ISO8859-1"), "UTF-8");
            response.setContentType("application/octet-stream");
            // URLEncoder.encode(fileNameString, "UTF-8") 下载文件名为中文的，文件名需要经过url编码
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            File file;
            String filePathString = path + fileName;
            file = new File(filePathString);
            fileIn = new FileInputStream(file);
            out = response.getOutputStream();

            byte[] outputByte = new byte[1024];
            int readTmp = 0;
            while ((readTmp = fileIn.read(outputByte)) != -1) {
                out.write(outputByte, 0, readTmp); //并不是每次都能读到1024个字节，所有用readTmp作为每次读取数据的长度，否则会出现文件损坏的错误
            }
        } catch (Exception e) {
            //log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (fileIn != null)
                    fileIn.close();
                if (out != null)
                    out.flush();
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 下载网络文件
     * @param fileUrl
     * @return
     * @throws Exception
     */
   public static boolean downloadNet(String fileUrl, HttpServletResponse response) throws Exception {
        ServletOutputStream out = null;
        boolean flag = false;
        // 取得文件名。
        response.setContentType("application/octet-stream");
        // URLEncoder.encode(fileNameString, "UTF-8") 下载文件名为中文的，文件名需要经过url编码
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        System.out.println(fileName);
        URL url = new URL(fileUrl);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setConnectTimeout(6000);
        urlCon.setReadTimeout(6000);
        int code = urlCon.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }
        //读文件流
        DataInputStream in = new DataInputStream(urlCon.getInputStream());
        //DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal + fileName));
        out = response.getOutputStream();
        byte[] buffer = new byte[2048];
        int count = 0;
        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        flag = true;
       return flag;
    }

}
